"use strict";
/**
 * 文本消息服务
 * Created by liamjung on 2018/6/25.
 */
const {ResponseWxError} = require("../../error/response_wx_error");
const AbstractService = require("../abstract_service");

class TextService extends AbstractService {

    async execute(wxMsg, mpConfig, pipeline) {

        let content = wxMsg.Content;

        let config = this.getRouteConfig(mpConfig, content);

        if (config.text) {
            //直接响应微信
            throw new ResponseWxError(config.text);
        } else {
            let openId = wxMsg.FromUserName;
            let createTime = +wxMsg.CreateTime;

            //MsgDTO
            let dto = {
                subjectId: mpConfig.subjectId,
                openId: openId,
                mpId: mpConfig.mpId,
                createTime: createTime,

                content: content
            };

            super.updateRequest(pipeline.request, config, dto);
        }
    }

    /**
     * 获取配置
     * @param mpConfig  公众号配置
     * @param keyword   文本消息关键字
     * @returns {{text, host, uri}}
     */
    getRouteConfig(mpConfig, keyword) {

        let routes = mpConfig["routes"];

        if (!routes) {
            //配置不存在时，直接响应微信
            throw new ResponseWxError("");
        }

        let contents = mpConfig["routes"]["content"];

        if (!contents) {
            //配置不存在时，直接响应微信
            throw new ResponseWxError("");
        }

        let content = contents[keyword];

        if (!content) {
            //配置不存在时，直接响应微信
            throw new ResponseWxError("");
        }

        return {
            text: content.text,
            host: content.host,
            uri: content.uri
        };
    }
}

module.exports = new TextService();